<div class="the-list" on:initialized>
  {#each safeItems as item, i (item)}
    <ListLazyItem
      {component}
      index={i}
      {length}
      {makeProps}
      key={item}
      on:initialized="itemInitialized()"
    />
  {/each}
</div>
<style>
  .the-list {
    position: relative;
  }
</style>
<script>
  import ListLazyItem from './ListLazyItem.html'
  import { listStore } from './listStore.js'
  import { getScrollContainer } from '../../_utils/scrollContainer.js'
  import { observe } from 'svelte-extras'
  import { mark, stop } from '../../_utils/marks.js'

  function getScrollTopOffset () {
    return document.getElementById('main-nav').getBoundingClientRect().height
  }

  export default {
    oncreate () {
      const { realm } = this.get()
      this.store.setCurrentRealm(realm)

      if (process.env.NODE_ENV !== 'production') {
        this.observe('safeItems', safeItems => {
          if (new Set(safeItems).size !== safeItems.length) {
            console.error('list of items is not unique:', safeItems)
          }
        })
      }
    },
    ondestroy () {
      this.store.setCurrentRealm(null)
    },
    methods: {
      observe,
      itemInitialized () {
        let { initializedCount, length } = this.get()
        initializedCount++
        this.set({ initializedCount })
        if (initializedCount === length) {
          this.initialize()
        }
      },
      initialize () {
        const { scrollToItem } = this.get()
        if (scrollToItem) {
          const element = document.getElementById(`list-item-${scrollToItem}`)
          requestAnimationFrame(() => {
            console.log('scrolling element into view')
            mark('scrollToElement')
            const scrollTopOffset = getScrollTopOffset()
            element.scrollIntoView(true)
            console.log('scrollTopOffset', scrollTopOffset)
            getScrollContainer().scrollTop -= scrollTopOffset
            stop('scrollToElement')
            this.fire('initialized')
          })
        } else {
          this.fire('initialized')
        }
      }
    },
    data: () => ({
      initializedCount: 0
    }),
    computed: {
      safeItems: ({ items }) => items || [],
      length: ({ safeItems }) => safeItems.length
    },
    components: {
      ListLazyItem
    },
    store: () => listStore
  }
</script>
